package com.glsc.ngateway.platform.service.softLegal;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.flow.cmdb.FlowFormPartInRepo;
import com.glsc.ngateway.platform.domain.softLegal.SoftChangeLog;
import com.glsc.ngateway.platform.domain.softLegal.SoftOut;
import com.glsc.ngateway.platform.repo.softLegal.SoftChangeLogRepository;
import com.glsc.ngateway.platform.repo.softLegal.SoftOutRepository;
import com.glsc.ngateway.platform.service.cmdb.SequenceProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

import static com.glsc.ngateway.common.api.common.enums.DictConstant.*;
import static com.glsc.ngateway.platform.utils.PlatformLocalConstant.SOFT_IN;
import static com.glsc.ngateway.platform.utils.PlatformLocalConstant.SOFT_OUT;

@Service
public class SoftOutService {

    @Autowired
    private SequenceProductService sequenceProductService;
    @Autowired
    private SoftOutRepository softOutRepository;
    @Autowired
    private SoftChangeLogRepository softChangeLogRepository;
    @Autowired
    private FlowFormPartInRepo flowFormPartInRepo;

    public Object search(Object paramsObj) {
        JSONObject objParmams = JSONObject.parseObject(JSONObject.toJSONString(paramsObj)).entrySet().stream()
                .filter(entry -> !entry.getValue().toString().isEmpty())
                .collect(JSONObject::new, (obj, entry) -> obj.put(entry.getKey(), entry.getValue()), JSONObject::putAll);

        if (StrUtil.isEmpty(objParmams.getString("orderByDirection"))) {
            objParmams.put("orderByDirection", "ASC");
        }
        if (StrUtil.isEmpty(objParmams.getString("orderByField"))) {
            objParmams.put("orderByField", "id");
        }
        Sort sort = Sort.by(Sort.Direction.fromString(objParmams.getString("orderByDirection")), objParmams.getString("orderByField"));

        Pageable pageable = PageRequest.of(objParmams.getInteger("pageNo") - 1, objParmams.getInteger("pageSize"), sort);

        SoftOut paramSearchDto = JSONObject.parseObject(JSONObject.toJSONString(objParmams), SoftOut.class);
        Page<SoftOut> result = softOutRepository.searchByParam(pageable, paramSearchDto);
//        result.getContent().forEach(e -> {
//            if (e.getCmdbCpuStandard() != null) {
//                e.setPartNum(e.getCmdbCpuStandard().getPartNum());
//            }
//        });
        return result;
    }

    /**
     * @param softOut
     * @param account       操作人员
     */
    public SoftOut addOrUpdate(SoftOut softOut, String account) {
        int addOrUpdateFlag = 0;
        softOut.setIsDelete(NO_DELETE);
        SoftChangeLog log = new SoftChangeLog();
        if (softOut.getId() != null) {
            // 修改
            log.setChangeType(DictConstant.UPDATE_STRING);
            addOrUpdateFlag = 2;
        } else {
            // 新增
            log.setChangeType(DictConstant.ADD_STRING);
            addOrUpdateFlag = 1;
        }
        //校验重复
//        if (addOrUpdateFlag != 0){
//            checkUnique(softOut, addOrUpdateFlag);
//        }
        log.setChangeContent(JSONObject.toJSONString(softOut));
        log.setChangeFrom(CMDB_CPU_DETAIL);
        log.setChangeId(softOut.getId() != null ? softOut.getId().toString() : null);
        log.setChangeUser(account);
        softChangeLogRepository.save(log);
        softOutRepository.save(softOut);
        return softOut;
    }

//    private void checkUnique(SoftOut softOut, int addOrUpdateFlag) {
//        if (StrUtil.isNotEmpty(softOut.getSoftwareName())) {
//            if (addOrUpdateFlag == 1) {
//                findSame(softOut);
//            } else {
//                //修改情况，要把已有结果查询出来，如果有变化还要校验
//                Optional<SoftOut> result = softOutRepository.findById(softOut.getId());
//                if (result.isPresent()) {
//                    if (result.get().getSoftwareName() != null && !result.get().getSoftwareName().equals(softOut.getSoftwareName())) {
//                        if (result.get().getIsDelete().equals(NO_DELETE)) {
//                            findSame(softOut);
//                        }
//                    }
//                    //修改情况存在未删除的记录
//                } else {
//                    findSame(softOut);
//                }
//            }
//
//        }
//    }

//    public void findSame(SoftOut softOut) {
//        List<SoftOut> result = softOutRepository.findAllBySoftwareNameAndIsDelete(softOut.getSoftwareName(), NO_DELETE);
//        if (CollectionUtil.isNotEmpty(result)) {
//            throw PlatformException.errorWithOutMail("名称重复");
//        }
////        if (!StrUtil.equals(CMDB_CONFIRM,cmdbConfirm)){
////            List<FlowFormPartIn> flowFormPartInDetails = flowFormPartInRepo.findFlowCpuSn(softOut.getSn());
////            if (CollectionUtil.isNotEmpty(flowFormPartInDetails)){
////                throw PlatformException.errorWithOutMail("有发起过的流程"+flowFormPartInDetails.get(0).getProcessTitle()+"存在相同的cpu序列号");
////            }
////        }
//
//    }

    public void delete(SoftOut softOut, String account) {
        SoftChangeLog log = new SoftChangeLog();
        log.setChangeContent(JSONObject.toJSONString(softOut));
        log.setChangeFrom(SOFT_OUT);
        log.setChangeId(softOut.getId().toString());
        log.setChangeUser(account);
        log.setChangeType(DELETE_STRING);
        Optional<SoftOut> optional = softOutRepository.findById(softOut.getId());
        if (optional.isPresent()) {
            SoftOut bean = optional.get();
            bean.setIsDelete(DELETED);
            softOutRepository.save(bean);
            softChangeLogRepository.save(log);
        } else {
            throw PlatformException.errorWithOutMail("删除记录不存在");
        }
    }

//    public void deleteByCodeList(List<String> codes, String account) {
//        SoftChangeLog log = new SoftChangeLog();
//        log.setChangeContent(JSONObject.toJSONString(codes));
//        log.setChangeFrom(CMDB_CPU_DETAIL);
//        log.setChangeUser(account);
//        log.setChangeType(DELETE_BATCH_STRING);
//        softChangeLogRepository.save(log);
//        softOutRepository.updateIsDeleteByCodes(DELETED, codes);
//    }

//    public void deleteByDeviceDetailId(Integer deviceDetailId, String operator) {
//        SoftChangeLog log = new SoftChangeLog();
//        log.setChangeContent(JSONObject.toJSONString(deviceDetailId));
//        log.setChangeFrom(CMDB_DEVICE_DETAIL);
//        log.setChangeUser(operator);
//        log.setChangeType(DELETE_BATCH_STRING);
//        softChangeLogRepository.save(log);
//        softOutRepository.updateIsDeleteByDeviceDetailId(DELETED, deviceDetailId);
//    }

//    public void outByDeviceDetail(CmdbDeviceDetail h, String operator) {
//        List<SoftOut> cpuDetails = softOutRepository.findAllByDeviceCodeAndIsDelete(h.getDeviceDetailCode(), NO_DELETED);
//        cpuDetails.stream().forEach(e -> e.setLifeStatus(PART_LIFE_CYCLE_OUT));
//        softOutRepository.saveAll(cpuDetails);
//        SoftChangeLog log = new SoftChangeLog();
//        log.setChangeContent(JSONObject.toJSONString(h.getDeviceDetailId()));
//        log.setChangeFrom(CMDB_DEVICE_DETAIL);
//        log.setChangeUser(operator);
//        log.setChangeType(UPDATE_STRING);
//        softChangeLogRepository.save(log);
//    }

//    public void outBySn(String sn, String operator) {
//        List<SoftOut> cpuDetails = softOutRepository.findAllBySnAndIsDelete(sn, NO_DELETE);
//        SoftOut cpuDetail = cpuDetails.get(0);
//        cpuDetail.setLifeStatus(PART_LIFE_CYCLE_OUT);
//        softOutRepository.save(cpuDetail);
//        SoftChangeLog log = new SoftChangeLog();
//        log.setChangeContent(JSONObject.toJSONString(sn));
//        log.setChangeFrom(CMDB_CPU_DETAIL);
//        log.setChangeUser(operator);
//        log.setChangeType(UPDATE_STRING);
//        softChangeLogRepository.save(log);
//    }

//    /**
//     * 根据序列号查询
//     * @param snList
//     * @return
//     */
//    public List<SoftOut> listBySn(List<String> snList) {
//        Map<String, Object> param = new HashMap<>();
//        param.put("INSTR_sn", StringUtils.join(snList,","));
//        param.put("EQ_isDelete", 0);
//
//        List<SoftOut> detailLis = softOutRepository.findAll(SpecificationUtil.buildSpecification(param, SoftOut.class));
//        return detailLis;
//    }
//
//    public List<SoftOut> listByDetailCode(List<String> collect) {
//        return softOutRepository.findAllByCpuDetailCodeIn(collect);
//    }
}
